//
//  ONEChatXMPPTool.m
//  ONEChat
//
//  Created by 楼楚 on 15/12/16.
//  Copyright © 2015年 Chu Lou. All rights reserved.
//

#import "ONEChatXMPPTool.h"
@interface ONEChatXMPPTool()<XMPPStreamDelegate>{
    XMPPResultBlock _resultBlock;
    XMPPvCardCoreDataStorage *_vCardStorge;//电子名片的数据储存
    XMPPvCardAvatarModule *_avatar;//头像模块
    XMPPReconnect *_reconnect;//自动连接模块
    XMPPMessageArchiving *_msgArchiving;//聊天模块
}
//1.初始化XMPPStream
- (void)setupXMPPStream;

// 2.连接到服务器【传一个jid】
- (void)connectToHost;

//3.连接到服务器成功后，再发送密码授权
- (void)sendPwdToHost;

//4.授权成功后，发送“在线”消息
- (void)sendOnlineToHost;

@end

@implementation ONEChatXMPPTool

singleton_implementation(ONEChatXMPPTool)

#pragma mark -初始化XMPPStream
- (void)setupXMPPStream
{
    _xmppStream = [[XMPPStream alloc]init];
    _reconnect = [[XMPPReconnect alloc]init];
    [_reconnect activate:_xmppStream];
    
    _vCardStorge = [XMPPvCardCoreDataStorage sharedInstance];
    _vCard = [[XMPPvCardTempModule alloc]initWithvCardStorage:_vCardStorge];
    
    //    激活
    [_vCard activate:_xmppStream];
    
    //    头像模块
    _avatar = [[XMPPvCardAvatarModule alloc]initWithvCardTempModule:_vCard];
    
    //    激活
    [_avatar activate:_xmppStream];
    
    _rosterStorge = [[XMPPRosterCoreDataStorage alloc]init];
    _roster = [[XMPPRoster alloc]initWithRosterStorage:_rosterStorge];
    [_roster activate:_xmppStream];
    
    _msgStorge = [[XMPPMessageArchivingCoreDataStorage alloc]init];
    _msgArchiving = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:_msgStorge];
    [_msgArchiving activate:_xmppStream];

//    设置代理
    
    [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    
}
#pragma mark - s释放xmppstream相关的资源
- (void)teardownXMPP
{
    //    移除代理
    [_xmppStream removeDelegate:self];
    //    停止模块
    [_reconnect deactivate];
    [_vCard deactivate];
    [_avatar deactivate];
    [_roster deactivate];
    [_msgArchiving deactivate];
    //    断开连接
    [_xmppStream disconnect];
    //    清空资源
     _reconnect = nil;
    _vCard = nil;
    _vCardStorge = nil;
    _avatar = nil;
    _roster = nil;
    _rosterStorge = nil;
    _msgArchiving = nil;
    _msgStorge = nil;
    _xmppStream = nil;
    
}

#pragma mark -连接到服务器
- (void)connectToHost
{
    
    NSLog(@"开始连接服务器");
    if (!_xmppStream) {
        [self setupXMPPStream];
    }
    
    NSString *user = nil;
    if (self.isRegisterOperation) {
        user = [ONEChatUserInfo sharedONEChatUserInfo].registerUser;
    }else
    {
        user = [ONEChatUserInfo sharedONEChatUserInfo].user;
    }
    
    XMPPJID *myJID = [XMPPJID jidWithUser:user domain:@"127.0.0.1" resource:@"iphone"];
    _xmppStream.myJID = myJID;
    _xmppStream.hostName = @"127.0.0.1";
    _xmppStream.hostPort = 5222;
    NSError *err = nil;
    if (![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&err]) {
        NSLog(@"%@",err);
    }
}
#pragma mark -发送密码授权
- (void)sendPwdToHost
{
    NSLog(@"发送密码授权");
    NSError *err = nil;
    NSString *pwd = [ONEChatUserInfo sharedONEChatUserInfo].pwd;
    [_xmppStream authenticateWithPassword:pwd error:&err];
    if (err) {
        NSLog(@"%@",err);
    }
}
#pragma mark -发送“在线”消息
- (void)sendOnlineToHost
{
    NSLog(@"发送在线消息");
    XMPPPresence *presence = [XMPPPresence presence];
    [_xmppStream sendElement:presence];
}

#pragma mark - 与主机连接成功

- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    NSLog(@"与主机连接成功");
    if (self.isRegisterOperation) {//发送注册密码
        NSString *pwd = [ONEChatUserInfo sharedONEChatUserInfo].registerPwd;
        [_xmppStream registerWithPassword:pwd error:nil];
        
    }else{
        //    与主机连接成功后，发送密码进行授权
        [self sendPwdToHost];
    }
}
#pragma mark - 与主机断开链接

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    //  如果有错误，代表连接失败
    
    //如果没有错误，标示正常的断开连接（人为的）
    if (error && _resultBlock) {
        _resultBlock(XMPPResultTypeNetErr);
    }
    NSLog(@"与主机断开连接 %@",error);
}
#pragma mark - 授权成功
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    NSLog(@"授权成功");
    [self sendOnlineToHost];
    //回调控制器登录成功
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginSuccess);
    }
}
#pragma mark - 授权失败

- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
    //判断block有无值，再回调给登录控制器
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeLoginFailue);
    }
    NSLog(@"授权失败%@",error);
}
#pragma mark - 注册成功
- (void)xmppStreamDidRegister:(XMPPStream *)sender
{
    NSLog(@"注册成功");
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeRegisterSuccess);
        NSLog(@"注册成功33333");
    }
}
#pragma mark - 注册失败

- (void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error{
    NSLog(@"注册失败 %@",error);
    if (_resultBlock) {
        _resultBlock(XMPPResultTypeRegisterFailue);
    }
}
#pragma mark - 公共方法
- (void)xmppUserlogout
{
   
    XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"];
    
    [_xmppStream sendElement:offline];
   
    [_xmppStream disconnect];
  
    [UIStoryboard showInitialVCWithName:@"Login"];
    
    [ONEChatUserInfo sharedONEChatUserInfo].loginStatus = NO;
    [[ONEChatUserInfo sharedONEChatUserInfo]saveUserInfoToSanbox];

    
}
- (void)xmppUserLogin:(XMPPResultBlock)resultBlock
{
  
    _resultBlock = resultBlock;
        if (_xmppStream.isConnected) {
        [_xmppStream disconnect];
    }
    
    [self connectToHost];
}
- (void)xmppUserRegister:(XMPPResultBlock)resultBlock
{
   
    _resultBlock = resultBlock;
   
    if (_xmppStream.isConnected) {
        [_xmppStream disconnect];
    }
    
    
    [self connectToHost];
}
- (void)dealloc
{
    [self teardownXMPP];
}
@end
